import $ from 'jquery';

export default {
    state: {
        cattleList: [],       // 当前牛场的所有牛只列表
        currentCattle: null, // 当前选中的牛只详细信息
        loading: false,      // 数据加载状态
        apiEndpoints: {
            list: "http://localhost:7090/api/cattle/list",
            add: "http://localhost:7090/api/cattle/add",
            update: "http://localhost:7090/api/cattle/update",
            delete: "http://localhost:7090/api/cattle/delete",
            detail: "http://localhost:7090/api/cattle/detail",
            temperatureHistory: "http://localhost:7090/api/cattle/temperatureHistory",
            weightHistory: "http://localhost:7090/api/cattle/weightHistory",
            searchByEarTag: "http://localhost:7090/api/cattle/searchByEarTag",
            locationHistory: "http://localhost:7090/api/cattle/locationHistory",
            sicknessHistory: "http://localhost:7090/api/cattle/sicknessHistory",
            allSicknessHistory: "http://localhost:7090/api/cattle/allSicknessHistory",
            listAll: "http://localhost:7090/api/cattle/listAll", // 添加新的API端点
            otherFinanceRecords: "http://localhost:7090/api/finance/records", // 其他财务记录
            addOtherFinanceRecord: "http://localhost:7090/api/finance/add", // 添加其他财务记录
            deleteOtherFinanceRecord: "http://localhost:7090/api/finance/delete", // 删除其他财务记录
        }
    },
    getters: {
        // 获取指定耳标的牛只
        getCattleByEarTag: (state) => (earTag) => {
            return state.cattleList.find(cattle => cattle.ear_tag === earTag);
        },
        getCattleById: (state) => (id) => {
            const numId = Number(id)
            return state.cattleList.find(c => c.id === numId)
        }
    },
    mutations: {
        // 更新牛只列表
        updateCattleList(state, list) {
            state.cattleList = list;
        },
        // 添加新牛只
        addCattle(state, newCattle) {
            state.cattleList.push(newCattle);
        },
        // 更新单头牛信息
        updateCattle(state, updatedCattle) {
            const index = state.cattleList.findIndex(c => c.id === updatedCattle.id);
            if (index !== -1) {
                state.cattleList.splice(index, 1, updatedCattle);
            }
        },
        // 删除牛只
        removeCattle(state, cattleId) {
            state.cattleList = state.cattleList.filter(c => c.id !== cattleId);
        },
        // 设置当前选中的牛
        setCurrentCattle(state, cattle) {
            state.currentCattle = cattle;
        },
        // 更新加载状态
        setLoading(state, status) {
            state.loading = status;
        }
    },
    actions: {
        // 获取所有牛只列表
        fetchCattleList({ commit, state }, data) {
            commit('setLoading', true);
            $.ajax({
                url: state.apiEndpoints.list,
                type: 'GET',
                headers: {
                    Authorization: `Bearer ${data.token}`,
                },
                success(resp) {
                    if (resp.status === "success") {
                        // console.log(resp);
                        commit('updateCattleList', resp.data);
                        data.success(resp);
                    } else {
                        data.error(resp);
                    }
                },
                error(resp) {
                    data.error(resp);
                },
                complete() {
                    commit('setLoading', false);
                }
            });
        },

        //  体温
        fetchTemperatureHistory({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: `${state.apiEndpoints.temperatureHistory}/${data.cattleId}?page=${data.page}&pageSize=${data.pageSize}`,
                    type: 'GET', // 根据后端实现保持GET请求
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        resolve(resp);
                        // console.log('分页响应数据:', resp);
                    },
                    error(err) {
                        reject(err);
                        console.error('分页请求失败:', err);
                    }
                });
            });
        },
        // 体重
        fetchWeightHistory({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: `${state.apiEndpoints.weightHistory}/${data.cattleId}?page=${data.page}&pageSize=${data.pageSize}`,
                    type: 'GET',
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        resolve(resp);
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },
        // 位置
        fetchLocationHistory({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: `${state.apiEndpoints.locationHistory}/${data.cattleId}?page=${data.page}&pageSize=${data.pageSize}`,
                    type: 'GET',
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        resolve(resp);
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },
        // 获取所有牛只的生病记录
        // 修改获取所有生病记录的方法
        fetchAllSicknessHistory({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: state.apiEndpoints.allSicknessHistory,
                    type: 'GET',
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        resolve(resp);
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },

        // 修改获取特定牛只生病记录的方法
        fetchSicknessHistory({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: `${state.apiEndpoints.sicknessHistory}/${data.cattleId}`,
                    type: 'GET',
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        resolve(resp);
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },

        fetchCattleByEarTag({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: `${state.apiEndpoints.searchByEarTag}/${data.earTag}`,
                    type: 'GET',
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        if (resp.status === "success") {
                            resolve(resp.data);
                        } else {
                            reject(resp.message);
                        }
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },

        // 更新牛只信息
        updateCattleInfo({ commit, state }, data) {
            $.ajax({
                url: `${state.apiEndpoints.update}/${data.cattleId}`,
                type: 'PUT',
                headers: {
                    Authorization: `Bearer ${data.token}`,
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify(data.formData),
                success(resp) {
                    if (resp.status === "success") {
                        commit('updateCattle', resp.data);
                        data.success(resp);
                    } else {
                        data.error(resp);
                    }
                },
                error(resp) {
                    data.error(resp);
                }
            });
        },

        // 获取牛只详细信息
        fetchCattleDetail({ commit, state }, data) {
            $.ajax({
                url: `${state.apiEndpoints.detail}/${data.cattleId}`,
                type: 'GET',
                headers: {
                    Authorization: `Bearer ${data.token}`
                },
                success(resp) {
                    if (resp.status === "success") {
                        commit('setCurrentCattle', resp.data);
                        data.success(resp);
                    } else {
                        data.error(resp);
                    }
                },
                error(resp) {
                    data.error(resp);
                }
            });
        },

        // 获取所有牛只（包括已出栏的）
        fetchAllCattleList({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: state.apiEndpoints.listAll,
                    type: 'GET',
                    headers: {
                        Authorization: `Bearer ${data.token}`,
                    },
                    success(resp) {
                        if (resp.status === "success") {
                            resolve(resp);
                        } else {
                            reject(resp);
                        }
                    },
                    error(resp) {
                        reject(resp);
                    }
                });
            });
        },

        // 获取其他财务记录
        fetchOtherFinanceRecords({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: state.apiEndpoints.otherFinanceRecords,
                    type: 'GET',
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        if (resp.status === "success") {
                            resolve(resp);
                        } else {
                            reject(resp);
                        }
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },

        // 添加其他财务记录
        addOtherFinanceRecord({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: state.apiEndpoints.addOtherFinanceRecord,
                    type: 'POST',
                    headers: {
                        Authorization: `Bearer ${data.token}`,
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(data.record),
                    success(resp) {
                        if (resp.status === "success") {
                            resolve(resp);
                        } else {
                            reject(resp);
                        }
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },

        // 删除其他财务记录
        deleteOtherFinanceRecord({ state }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: `${state.apiEndpoints.deleteOtherFinanceRecord}/${data.id}`,
                    type: 'DELETE',
                    headers: {
                        Authorization: `Bearer ${data.token}`
                    },
                    success(resp) {
                        if (resp.status === "success") {
                            resolve(resp);
                        } else {
                            reject(resp);
                        }
                    },
                    error(err) {
                        reject(err);
                    }
                });
            });
        },

        // 添加牛只
        addCattle({ state, commit }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: state.apiEndpoints.add,
                    type: 'POST',
                    headers: {
                        Authorization: `Bearer ${data.token}`,
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(data.cattle),
                    success(resp) {
                        if (resp.status === "success") {
                            commit('addCattle', resp.data);
                            resolve(resp);
                        } else {
                            reject(resp);
                        }
                    },
                    error(resp) {
                        reject(resp);
                    }
                });
            });
        },

        // 删除牛只
        deleteCattle({ state, commit }, data) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: state.apiEndpoints.delete,
                    type: 'POST',
                    headers: {
                        Authorization: `Bearer ${data.token}`,
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(data.deathCattle),
                    success(resp) {
                        if (resp.status === "success") {
                            commit('removeCattle', data.deathCattle.cattleId);
                            resolve(resp);
                        } else {
                            reject(resp);
                        }
                    },
                    error(resp) {
                        reject(resp);
                    }
                });
            });
        }
    }
}
